package org.zhxy.core.quality.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.zhxy.common.aop.AutomaticLog;
import org.zhxy.common.config.MapperFactory;
import org.zhxy.common.config.ServiceFactory;
import org.zhxy.common.error.CommonException;
import org.zhxy.common.response.Result;
import org.zhxy.common.response.ResultCode;
import org.zhxy.common.utils.*;
import org.zhxy.entity.quality.ExcelStudentBean;
import org.zhxy.entity.quality.Student;
import org.zhxy.entity.system.User;

import java.io.IOException;
import java.text.ParseException;
import java.util.*;

@RestController
@RequestMapping("/studentManager")
public class StudentManagerController {

    @RequestMapping(value = "/getStudentList",method = RequestMethod.POST)
    public Result getStudentList(@RequestBody Map<String, Object> map) throws CommonException {
        return Result.SUCCESS_NO_MESSAGE(ServiceFactory.studentManagerService.getStudentList(map));
    }


    @AutomaticLog("上传excel学生信息")
    @RequestMapping(value = "/importExcel",method = RequestMethod.POST)
    public Result importExcel(@RequestParam("file")MultipartFile file) throws CommonException, IOException, ParseException {
        String fileName = file.getOriginalFilename();
        if (StringUtils.isEmpty(fileName)) throw new CommonException(ResultCode.FILE_EMPTY);

        List<ExcelStudentBean> errorData = new ArrayList<>();

        String[] excelHead={
                "序号","是否报档","班级",
                "姓名","性别","手机","父母联系方式","身份证号",
                "出生年月","开班日期","入学年龄",
                "当前年龄","毕业日期","毕业年龄",
                "成绩","来源","入学学历",
                "中专注册时间","中专","成考",
                "省","市","县/区",
                "镇/乡","村","毕业院校"};

        String[] excelHeadAlias={
                "ignoreA","hasRegister","ignoreB",
                "nickName","sex","telephone","emergencyContact","idCard",
                "ignoreC","ignoreD","ignoreE",
                "ignoreF","ignoreG","ignoreH",
                "ignoreI","originate","education",
                "transitRegisterTime","transitSource","hasEstablish",
                "province","city","area",
                "township","detailed","graduationSchool"};
        List<ExcelStudentBean> beans = HutoolExcelUtils.importExcel(file.getInputStream(), excelHead, excelHeadAlias, ExcelStudentBean.class);
        for (ExcelStudentBean bean : beans) {
            if(bean != null){
                String idCard = bean.getIdCard();
                if(org.springframework.util.StringUtils.isEmpty(idCard)){
                    errorData.add(bean);
                    continue;
                }else{
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq(Constants.DB.ID_CARD,idCard);
                    User target = MapperFactory.userMapper.selectOne(queryWrapper);
                    if(target != null){
                        errorData.add(bean);
                        continue;
                    }else{
                        String id = new IdWorker().nextId();
                        User user = User.builder()
                                .id(id)
                                .username(bean.getNickName() == null ? null : PinYinUtil.toPinyin(bean.getNickName()))
                                .password("123456")
                                .nickName(bean.getNickName())
                                .level("user")
                                .telephone(bean.getTelephone())
                                .sex(bean.getSex() == null ? null : bean.getSex().equals("男") ? "1" : (bean.getSex().equals("女") ? "2" : null))
                                .type("2")
                                .idCard(bean.getIdCard())
                               // .birthday(bean.getIdCard() == null ? null : new SimpleDateFormat("yyyy-MM-dd").parse(IdCardUtils.getBirthByIdCard(bean.getIdCard())))
                                .status("1")
                                .province(bean.getProvince())
                                .city(bean.getCity())
                                .area(bean.getArea())
                                .township(bean.getTownship())
                                .detailed(bean.getDetailed())
                                .education(bean.getEducation())
                                .graduationSchool(bean.getGraduationSchool())
                                .major("暂无")
                                .emergencyContact(bean.getEmergencyContact())
                                .emergencyRelation("家人")
                                .url(null)
                                .build();

                        MapperFactory.userMapper.insert(user);

                        Student student = Student.builder()
                                .id(id)
                                .nickName(bean.getNickName())
                                .hasRegister(bean.getHasRegister() == null ? null : (bean.getHasRegister().equals("是") ? "1" : "2"))
                                .originate(bean.getOriginate())
                                .enterTime(null)
                       //         .enterAge(null)
                      //          .transitRegisterTime(bean.getTransitRegisterTime() == null ? null : new SimpleDateFormat("yyyy年MM月").parse(bean.getTransitRegisterTime()))
                                .transitSource(bean.getTransitSource())
                                .hasEstablish(bean.getHasEstablish() == null ? null : (bean.getHasEstablish().equals("有") ? "1" : "2"))
                                .studyType("1")
                                .build();
                        MapperFactory.studentManagerMapper.insert(student);
                    }
                }
            }
        }

        System.out.println(errorData);

        return Result.SUCCESS();
    }


    @RequestMapping(value = "/replaceClassesByStudentId",method = RequestMethod.POST)
    public Result replaceClassesByStudentId(@RequestBody Map<String, Object> map){
        return ServiceFactory.studentManagerService.replaceClassesByStudentId(map);
    }

}
